import asyncore
import os
import sys
import time

from application import SchedulerApplication
from logger import LoggerListener

"""
daemonize: run procedure with function and arguments
"""
def daemonize(func_ref, **kwargs):
    """
    Fork child and execute process
    """
    try:
        pid = os.fork()
        if pid > 0:
            return pid
        elif pid == 0:
            func_ref(**kwargs)
            sys.exit(0)
    except OSError,e:
        print ("[ERROR][daemonize] %s" % (str(e)))
        sys.exit(-1)


"""
launch_scheduler_process: run scheduler process
"""
def launch_scheduler_process(**kwargs):
     scheduler_app = SchedulerApplication('ThreadPool', kwargs["max_worker"])
     scheduler_app.start_scheduler()
     time.sleep(kwargs["interval_check"])
     while True:
        scheduler_app.refresh_jobs()
        time.sleep(kwargs["interval_check"])
     scheduler_app.stop_scheduler()
     sys.exit(0)


"""
launch_logger_process: run logger process
"""
def launch_logger_process(**kwargs):
    print ("[PID %d]Start LoggerListener......" % (os.getpid()))
    LoggerListener(kwargs["logger_sock"])
    asyncore.loop(5, True)
    sys.exit(0)
